package com.ruoyi.web.controller.combat.weibo;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.combat.domain.SpiderWeiboQrVO;
import com.ruoyi.combat.domain.useralignment.CombatUserWb;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.service.useralignment.ICombatUserWbService;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.util.weibo.WeiboUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.HttpCookie;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/spider/toolbox")
@Anonymous
@Api(tags = "微博登录")
public class SpiderToolBoxController {

    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private ICombatUserWbService combatUserWbService;
    @Autowired
    private WeiboUtil weiboUtil;

    /**
     * 功能描述：微博二维码获取
     *
     * @return {@link R }<{@link SpiderWeiboQrVO }>
     * @author youzai
     * @date 2023/12/06
     */
    @GetMapping("/weiboQrCodeByPhoneNumber")
    @ApiOperation("微博二维码获取")
    public AjaxResult weiboQrCode(@RequestParam(value = "phoneNumber") String phoneNumber) {
        CombatUser combatUser = new CombatUser();
        combatUser.setUserPhone(phoneNumber);
        List<CombatUser> combatUserList = combatUserService.selectCombatUserList(combatUser);
        CombatUserWb combatUserWb = new CombatUserWb();
        combatUserWb.setUserPhone(phoneNumber);
        List<CombatUserWb> combatUserWbList = combatUserWbService.selectCombatUserWbList(combatUserWb);
        String userId = "";
        Date authTime = null;
        SpiderWeiboQrVO spiderWeiboQrVO = new SpiderWeiboQrVO();
        if(combatUserList.size()>0||combatUserWbList.size()>0){
            if(combatUserList.size()>0){
                CombatUser combatUser1 = combatUserList.get(0);
                if(combatUser1.getAuthTime()!=null) {
                    authTime = combatUser1.getAuthTime();
                }
                userId = combatUser1.getUserId();
            }
            if (combatUserWbList.size()>0){
                CombatUserWb combatUserWb1 = combatUserWbList.get(0);
                if(combatUserWb1.getAuthTime()!=null) {
                    authTime = combatUserWb1.getAuthTime();
                }
                userId = combatUserWb1.getUserId();
            }
        }else{
            return AjaxResult.success(spiderWeiboQrVO);
        }
        String imageUrl = weiboUtil.getQrcodelogin(userId);
        spiderWeiboQrVO.setAuthTime(authTime);
        spiderWeiboQrVO.setQRid(userId);
        spiderWeiboQrVO.setImgUrl(imageUrl);
        spiderWeiboQrVO.setUserId(userId);
        return AjaxResult.success(spiderWeiboQrVO);
    }
    /**
     * 功能描述：微博二维码获取
     *
     * @return {@link R }<{@link SpiderWeiboQrVO }>
     * @author youzai
     * @date 2023/12/06
     */
    @GetMapping("/weiboQrCode")
    @ApiOperation("微博二维码获取")
    public R<SpiderWeiboQrVO> weiboQrCode() {
        HttpResponse response = HttpUtil.createGet("https://login.sina.com.cn/sso/qrcode/image?entry=weibo&size=180&callback=STK_" + System.currentTimeMillis())
                .header("Referer", "https://weibo.com/")
                .execute();
        String regex = "\"qrid\":\"([^\"]+)\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(response.body());
        String qrid = "";
        if (matcher.find()) {
            qrid = matcher.group(1);
        } else {
            return R.fail("二维码获取失败！");
        }
        String jsonText = response.body().substring(response.body().indexOf("(") + 1, response.body().lastIndexOf(")"));
        JSONObject jsonObject = JSON.parseObject(jsonText);
        String imageUrl = jsonObject.getJSONObject("data").getString("image");
        SpiderWeiboQrVO spiderWeiboQrVO = new SpiderWeiboQrVO();
        spiderWeiboQrVO.setQRid(qrid);
        spiderWeiboQrVO.setImgUrl(imageUrl);
        return R.ok(spiderWeiboQrVO);
    }

    /**
     * 功能描述：微博登录
     *
     * @param qrid
     * @return {@link R }<{@link String }>
     * @author youzai
     * @date 2023/12/06
     */
    @GetMapping("/weiboLogin")
    @ApiOperation("判断微博登录是否成功")
    public AjaxResult weiboLogin(@RequestParam("qrid") String qrid, @RequestParam("userId") String userId) {
        boolean login = weiboUtil.isLogin(userId);
        if (!login){
            Map map = new HashMap();
            map.put("retcode", "201");
            return AjaxResult.success("登录失败！");
        }

        String token = System.currentTimeMillis() + "";
        CombatUser combatUser = new CombatUser();
        combatUser.setUserId(userId);
        Date date = new Date();
        List<CombatUser> combatUserList = combatUserService.selectCombatUserList(combatUser);
        if(combatUserList.size()>0){
            CombatUser combatUser1 = combatUserList.get(0);
            combatUser1.setToken(token);
            combatUser1.setAuthTime(date);
            combatUserService.updateCombatUser(combatUser1);
        }
        CombatUserWb combatUserWb = new CombatUserWb();
        combatUserWb.setUserId(userId);
        List<CombatUserWb> combatUserWbList = combatUserWbService.selectCombatUserWbList(combatUserWb);
        if(combatUserWbList.size()>0){
            CombatUserWb combatUserWb1 = combatUserWbList.get(0);
            combatUserWb1.setToken(token);
            combatUserWb1.setAuthTime(date);
            combatUserWbService.updateCombatUserWb(combatUserWb1);
        }
        Map map = new HashMap();
        map.put("retcode", "200");
        map.put("data", token);
        return AjaxResult.success("success",map);
    }

    /**
     * 功能描述：获取cookie
     *
     * @param cookies
     * @return {@link String }
     * @author youzai
     * @date 2023/12/06
     */
    private static String getCookieString(List<HttpCookie> cookies) {
        StringBuilder cookieBuilder = new StringBuilder();
        HashMap<String, String> cookieMap = new HashMap<>();
        //去重
        for (HttpCookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            if (!cookieMap.containsKey(name)) {
                cookieMap.put(name, value);
            }
        }
        //拼装
        for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            String keyValueString = key + "=" + value;
            cookieBuilder.append(keyValueString).append("; ");
        }
        //最终结果
        String finalCookie = cookieBuilder.toString();
        if (finalCookie.endsWith("; ")) {
            finalCookie = finalCookie.substring(0, finalCookie.length() - 2);
        }
        return finalCookie;
    }


}